unit Rails.Vcl.Controls;

interface

uses
  Vcl.ExtCtrls, System.Generics.Collections, System.Classes, Rails.Vcl.Fields,
  Vcl.Controls, System.SysUtils, System.Types, Vcl.Forms, Rails.Vcl.Interfaces,
  Aurelius.Mapping.Explorer, Rails.Metadata;

type
  TControls<T: class> = class(TPanel, IControls)
  private
    Position: TPoint;
    FFields: TFields;
    Scroll: TFrame;
  protected
    procedure BeforeFieldCreate(Column: TRailsColumn; Parent: TWinControl; var Position: TPoint; var AutoCreate: Boolean); virtual;
    procedure AfterFieldCreate(Column: TRailsColumn; FieldComponents: array of TObject); overload; virtual;
    procedure AfterFieldCreate(Column: TRailsColumn; FieldPanel:TPanel); overload; virtual;
  public
    property Fields: TFields read FFields;
    constructor Create(AOwner: TWinControl); reintroduce;
    procedure Bind(AObj: T);
    destructor Destroy; override;
  end;

implementation

uses
  RTTI, Rails.Vcl.Field, Dialogs, TypInfo, Aurelius.Mapping.Attributes,
  Aurelius.Mapping.Metadata;

{ TControls<T> }

procedure TControls<T>.AfterFieldCreate(Column: TRailsColumn; FieldComponents: array of TObject);
begin

end;

procedure TControls<T>.AfterFieldCreate(Column: TRailsColumn; FieldPanel: TPanel);
begin

end;

procedure TControls<T>.BeforeFieldCreate(Column: TRailsColumn; Parent: TWinControl;
  var Position: TPoint; var AutoCreate: Boolean);
begin
  AutoCreate := True;
end;

procedure TControls<T>.Bind(AObj: T);
begin

end;

constructor TControls<T>.Create(AOwner: TWinControl);
var
  Ctx: TRttiContext;
  Typ: TRttiInstanceType;
  IdsGen: TObjectList<TColumn>;
  Attr: TCustomAttribute;
  Col: TRailsColumn;
begin
  inherited Create(nil);
  Parent := AOwner;
  Align := alClient;
  Scroll := TFrame.Create(Self);
  Scroll.AutoScroll := True;
  Scroll.HorzScrollBar.Position := 0;
  Scroll.Parent := Self;
  Scroll.Align := alClient;

  FFields := TFields.Create;
  Col := nil;
  Position.X := 0;
  Position.Y := 0;

  Ctx := TRttiContext.Create;
  Typ := Ctx.GetType(TypeInfo(T)) as TRttiInstanceType;
  IdsGen := TObjectList<TColumn>.Create(False);
  try
    for Attr in Typ.GetAttributes do
    begin
      if (Attr is  Id) then
      begin
        if Id(Attr).Generator = TIdGenerator.IdentityOrSequence then
          IdsGen.Add(TMappingExplorer.DefaultInstance.GetColumnByPropertyName(Typ.MetaclassType, Id(Attr).MemberName));
      end;
    end;

    for Col in TRailsExplorer.GetIntance.GetColumns(Typ.MetaclassType) do
    begin
      if not IdsGen.Contains(Col.ColumnInfo) then
        FFields.Add(TField.Create(Col, Scroll, Self, Position));
    end;

  finally
    FreeAndNil(IdsGen);
  end;
end;

destructor TControls<T>.Destroy;
begin
  FreeAndNil(FFields);
  inherited;
end;

end.
